package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("CrawlerfilestatusRestController")
public class CrawlerfilestatusRestController extends CmiEmaController {

	/**
	 * Create a new Crawlerfilestatus entity
	 * 
	 */
	@RequestMapping(value = "/newCrawlerfilestatus", method = RequestMethod.POST)
	@ResponseBody
	public Object newCrawlerfilestatus(@RequestBody Crawlerfilestatus crawlerfilestatus) {
		crawlerfilestatusService.saveCrawlerfilestatus(crawlerfilestatus);
		return JSONObject.parse(cmiPsonService
				.toJsonString(crawlerfilestatusDAO.findCrawlerfilestatusByPrimaryKey(crawlerfilestatus.getId()), 2));
	}

	@RequestMapping(value = "/restNewCrawlerfilestatus", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewCrawlerfilestatus(@RequestBody String crawlerfilestatusJson) {
		Crawlerfilestatus crawlerfilestatus = new Gson().fromJson(crawlerfilestatusJson, Crawlerfilestatus.class);
		appendReferences(crawlerfilestatus);
		crawlerfilestatusService.saveCrawlerfilestatus(crawlerfilestatus);
		return JSONObject.parse(cmiPsonService
				.toJsonString(crawlerfilestatusDAO.findCrawlerfilestatusByPrimaryKey(crawlerfilestatus.getId()), 2));
	}

	@RequestMapping(value = "/saveCrawlerfilestatus", method = RequestMethod.PUT)
	@ResponseBody
	public Crawlerfilestatus saveCrawlerfilestatus(@RequestBody Crawlerfilestatus crawlerfilestatus) {
		crawlerfilestatusService.saveCrawlerfilestatus(crawlerfilestatus);
		return crawlerfilestatusDAO.findCrawlerfilestatusByPrimaryKey(crawlerfilestatus.getId());
	}

	@RequestMapping(value = "/restSaveCrawlerfilestatus", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveCrawlerfilestatus(@RequestBody String crawlerfilestatusJson) {
		Crawlerfilestatus crawlerfilestatus = new Gson().fromJson(crawlerfilestatusJson, Crawlerfilestatus.class);
		appendReferences(crawlerfilestatus);
		CmiPsonService cmiPsonService = new CmiPsonService();
		crawlerfilestatusService.saveCrawlerfilestatus(crawlerfilestatus);
		return JSONObject.parse(cmiPsonService
				.toJsonString(crawlerfilestatusDAO.findCrawlerfilestatusByPrimaryKey(crawlerfilestatus.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteCrawlerfilestatus/{crawlerfilestatusId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteCrawlerfilestatus(@PathVariable Integer crawlerfilestatusId) {
		Crawlerfilestatus crawlerfilestatus = crawlerfilestatusDAO
				.findCrawlerfilestatusByPrimaryKey(crawlerfilestatusId);
		crawlerfilestatusService.deleteCrawlerfilestatus(crawlerfilestatus);
	}

	@RequestMapping(value = "/restConfirmDeleteCrawlerfilestatuss")
	@ResponseBody
	public Object restConfirmDeleteCrawlerfilestatuss(@RequestBody Set<Integer> deleteCrawlerfilestatussIds) {
		Set<Crawlerfilestatus> deleteCrawlerfilestatuss = crawlerfilestatusDAO
				.findCrawlerfilestatussByIds(deleteCrawlerfilestatussIds);
		Set<Crawlerfilestatus> referencedCrawlerfilestatuss = crawlerfilestatusService
				.loadReferenceCrawlerfilestatuss(deleteCrawlerfilestatuss);
		deleteCrawlerfilestatuss.removeAll(referencedCrawlerfilestatuss);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedCrawlerfilestatuss);
		jsonObject.put("deleteEntitys", deleteCrawlerfilestatuss);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteCrawlerfilestatuss")
	@ResponseBody
	public Object restDeleteCrawlerfilestatuss(@RequestBody Set<Crawlerfilestatus> deleteCrawlerfilestatuss) {
		Iterator<Crawlerfilestatus> iterator = deleteCrawlerfilestatuss.iterator();
		while (iterator.hasNext()) {
			Crawlerfilestatus currentCrawlerfilestatus = iterator.next();
			crawlerfilestatusService.deleteCrawlerfilestatus(currentCrawlerfilestatus);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listCrawlerfilestatuss");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadCrawlerfilestatus/{crawlerfilestatusId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerfilestatus(@PathVariable Integer crawlerfilestatusId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(crawlerfilestatusDAO.findCrawlerfilestatusByPrimaryKey(crawlerfilestatusId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadCrawlerfilestatusCrawlerfiles/{crawlerfilestatusId}/crawlerfiles/{relatedcrawlerfileId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerfilestatusCrawlerfiles(@PathVariable Integer crawlerfilestatusId,
			@PathVariable Integer relatedcrawlerfileId, @RequestBody CmiPagination cmiPagination) {
		Crawlerfile crawlerfile = crawlerfileDAO.findCrawlerfileByPrimaryKey(relatedcrawlerfileId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(crawlerfile, 2, cmiPagination));
	}

	public void appendReferences(Crawlerfilestatus crawlerfilestatus) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Crawlerfile> crawlerfilesForCrawlerfilestatus = new HashSet<>();
		for (Crawlerfile crawlerfile_Crawlerfilestatus : crawlerfilestatus.getCrawlerfilesForCrawlerfilestatus()) {
			crawlerfilesForCrawlerfilestatus
					.add(crawlerfileService.findCrawlerfileByPrimaryKey(crawlerfile_Crawlerfilestatus.getId()));
		}
		crawlerfilestatus.setCrawlerfilesForCrawlerfilestatus(crawlerfilesForCrawlerfilestatus);
	}

	@RequestMapping(value = "/restGetCrawlerfilestatusCrawlerfiles/{crawlerfilestatusId}/crawlerfiles", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetCrawlerfilestatusCrawlerfiles(@PathVariable Integer crawlerfilestatusId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(crawlerfilestatusDAO.findCrawlerfilestatusByPrimaryKey(crawlerfilestatusId)
						.getCrawlerfilesForCrawlerfilestatus(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListCrawlerfilestatuss", method = RequestMethod.GET)
	@ResponseBody
	public Object restListCrawlerfilestatuss() {
		return JSONObject.parse(cmiPsonService.toJsonString(crawlerfilestatusService.loadCrawlerfilestatuss(), 2));
	}

	@RequestMapping(value = "/restListCrawlerfilestatussPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListCrawlerfilestatussPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = crawlerfilestatusPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Crawlerfilestatus> crawlerfilestatuss = crawlerfilestatusDAO.findAllCrawlerfilestatuss(startResult,
				cmiPagination.getPaginationSize());
		String crawlerfilestatusString = cmiPsonService.toPsonString(crawlerfilestatuss, 2, cmiPagination);

		return JSONObject.parse(crawlerfilestatusString);
	}

	@RequestMapping("/crawlerfilestatusSelectBox")
	@ResponseBody
	public JSONObject crawlerfilestatusSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Crawlerfile":
				entitySet = crawlerfileService.loadCrawlerfilesByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Crawlerfile":
				entitySet = crawlerfileDAO.findAllCrawlerfiles((pageNumber - 1) * paginationSize, paginationSize);
				count = crawlerfileService.countCrawlerfiles();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Crawlerfile":
				entitySet = crawlerfileDAO.findCrawlerfileByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = crawlerfileService.countCrawlerfilesByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
